from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
import uuid
from accounts.models import Teacher, Student
import os

class Course(models.Model):
    """课程模型"""
    title = models.CharField(_("课程标题"), max_length=200)
    slug = models.SlugField(_("课程标识"), max_length=200, unique=True)
    teacher = models.ForeignKey(
        Teacher,
        on_delete=models.CASCADE,
        verbose_name=_("讲师"),
        related_name='courses'
    )
    description = models.TextField(_("课程描述"))
    learning_objectives = models.TextField(_("学习目标"), blank=True)
    requirements = models.TextField(_("课程要求"), blank=True)
    duration = models.IntegerField(_("预计时长（小时）"), default=1)
    status = models.CharField(_("课程状态"), max_length=20)
    published_at = models.DateTimeField(_("发布时间"), blank=True, null=True)
    created_at = models.DateTimeField(_("创建时间"), auto_now_add=True)
    updated_at = models.DateTimeField(_("更新时间"), auto_now=True)
    students = models.ManyToManyField(
        Student,
        through='Enrollment',
        verbose_name=_("学生"),
        related_name='enrolled_courses'
    )

    class Meta:
        verbose_name = _("课程")
        verbose_name_plural = _("课程")
        ordering = ['-created_at']

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('course_detail', kwargs={'slug': self.slug})

    def get_enrollment_count(self):
        return self.enrollments.count()




class Enrollment(models.Model):
    """学生选课记录"""
    student = models.ForeignKey(
        Student,
        on_delete=models.CASCADE,
        verbose_name=_("学生"),
        related_name='enrollments'
    )
    course = models.ForeignKey(
        Course,
        on_delete=models.CASCADE,
        verbose_name=_("课程"),
        related_name='enrollments'
    )
    enrolled_at = models.DateTimeField(_("选课时间"), auto_now_add=True)
    completed_at = models.DateTimeField(_("完成时间"), blank=True, null=True)
    progress = models.IntegerField(_("学习进度"), default=0)
    is_completed = models.BooleanField(_("是否完成"), default=False)

    class Meta:
        verbose_name = _("选课记录")
        verbose_name_plural = _("选课记录")
        unique_together = ['student', 'course']
        ordering = ['-enrolled_at']

"""课程电子书籍文件上传"""
class CourseMaterial(models.Model):
    course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='materials')
    title = models.CharField(max_length=255)
    file = models.FileField(upload_to='course_materials/')
    file_type = models.CharField(max_length=50, blank=True, null=True)
    uploader = models.ForeignKey(Teacher, on_delete=models.SET_NULL, null=True)
    uploaded_at = models.DateTimeField(auto_now_add=True)
    file_size = models.BigIntegerField(verbose_name='文件大小（字节）', default=0)

    def __str__(self):
        return f"{self.title} ({self.course.title})"

    def get_file_extension(self):
        name, extension = os.path.splitext(self.file.name)
        return extension.lower()